<template>
    <popup
        :show="true"
        :title="'重置密码'"
        :loading="loading"
        :async-close="true"
        width="500px"
        @close="emits('close')"
        @confirm="handleSubmit"
    >
        <div class="p-6 pb-0">
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                @submit.prevent
            >
                <el-form-item label="密码设置" prop="password">
                    <el-input type="password" v-model="formData.password" show-password />
                </el-form-item>
            </el-form>
        </div>
    </popup>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import feedback from '@/utils/feedback'
import userApi from '@/api/users/user'

const emits = defineEmits(['close', 'success'])
const formRef = shallowRef<FormInstance>()

const props = defineProps({
    user_id: {
        type: Number,
        default: 0
    }
})

// 表单数据
const loading = ref<boolean>(false)
const formData = reactive({
    user_id: props.user_id,
    password: ''
})

// 表单规则
const formRules: FormRules = {
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度必须介于 6 和 20 之间', trigger: 'blur' },
        { pattern: /^[^<>"'|\\]+$/, message: "密码不能包含非法字符：< > \" ' \\\ |", trigger: 'blur' }
    ] as any[]
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
    await formRef.value?.validate().then(async () => {
        loading.value = true
        await userApi.resetPassword(props.user_id, formData.password)
            .finally(() => {
                loading.value = false
            })

        feedback.msgSuccess('重置成功')
        emits('close')
        emits('success')
    }).catch(() => {})
}
</script>
